import { ref, reactive, computed, watch } from 'vue'

const init = (props, emit) => {
  /** 组件权限 */
  const isDetail = computed(() => {
    if (props.detail) {
      return true
    }
    return props.item.permission > 0
  })

  /** v-model */
  const fieldModel = computed({
    get() {
      if (isDetail.value && !props.modelValue) {
        if (props.item.type === 'number' || props.item.type === 'computedays') {
          return '0'
        }
        if (!props.item.options.append) {
          return '--'
        }
      }
      return props.modelValue
    },
    set(val) {
      if (!props.designer) {
        emit('update:modelValue', val)
      }
    }
  })

  /** 更新默认值，初始化默认值 */
  watch(
    () => props.item.options.defaultValue,
    (val) => {
      if (!props.modelValue) {
        fieldModel.value = val
      }
      if (Array.isArray(props.modelValue) && props.modelValue.length === 0) {
        fieldModel.value = val
      }
      // 设计器中修改默认值显示
      if (props.designer) {
        emit('update:modelValue', val)
      }
    },
    { immediate: true }
  )

  /** 校验规则, 隐藏组件、只读组件不校验 */
  let rules = reactive([
    {
      required: !props.item.options.hidden && !props.item.options.readonly && props.item.options.required,
      message: props.h5 ? '' : props.item.options.requiredMessage,
      trigger: 'blur'
    }
  ])

  /**
   * 表单组件事件处理
   */
  const events = computed(() => props.item.events || {})
  const { onChange, onFocus, onBlur, onValidate } = events.value

  if (onValidate && !props.item.options.hidden && !props.item.options.readonly) {
    if (props.h5) {
      const customFn = (value) => {
        return new Promise((resolve) => {
          const validateFn = new Function('value', 'formData', 'callback', onValidate)
          let errorMsg = true
          const callback = (msg) => {
            if (msg) {
              errorMsg = msg
            }
            resolve(errorMsg)
          }
          validateFn(value, props.formData, callback)
        })
      }
      rules.push({
        validator: customFn
      })
    } else {
      const customFn = (rule, value, callback) => {
        const validateFn = new Function('value', 'formData', 'callback', onValidate)
        const _callback = (msg) => {
          if (msg) {
            callback(new Error(msg))
          }
          callback()
        }
        validateFn(value, props.formData, _callback)
      }
      rules.push({
        validator: customFn,
        trigger: ['blur', 'change']
      })
    }
  }

  const handleChangeEvent = (val) => {
    if (onChange) {
      const changeFn = new Function('value', 'formData', onChange)
      changeFn(val, props.formData)
    }
  }
  const handleBlurEvent = (event) => {
    if (onFocus) {
      const blurFn = new Function('event', onFocus)
      blurFn(event)
    }
  }
  const handleFocusEvent = (event) => {
    if (onBlur) {
      const focusFn = new Function('event', onBlur)
      focusFn(event)
    }
  }

  /** 手动处理change事件, 为了兼容H5端  */
  watch(
    () => props.modelValue,
    (val) => {
      handleChangeEvent(val)
    }
  )

  /**
   * 设计器中取消表单验证
   */
  if (props.designer) {
    rules = reactive([])
  }

  return {
    isDetail,
    fieldModel,
    rules,
    handleBlurEvent,
    handleFocusEvent
  }
}

export default init
